#!usr/bin/python
# coding=utf-8

import json
import time
import requests
from logger import logger
from managers import globalarea


class rom(object):

    def request_package(self, model, profile, deploy, private_logger, mi_account_name):
        for count in xrange(3):
            host = "http://corgi.pt.miui.com/open-api/buildRom"
            params = {"user": mi_account_name,
                      "model": model,
                      "profile": profile,
                      "deploy": deploy,
                      "virant": "default",
                      "buildLabel": "today-alpha",
                      "enable_miui_debugging": "true"}
            result = requests.post(host, data=params)
            result_json = json.loads(result.text)
            if result_json.get('result') == 'success':
                jobid = result_json.get('id')
                private_logger.info("创建构建ROM的任务, id:%s" % str(jobid))
                return jobid
            else:
                private_logger.info("Jenkins创建构建ROM的任务失败, msg: %s" % str(result_json.get('msg')))
                # print 'Jenkins create a job failure. The %s attempt now ...' % str(count + 1)
                continue

    def check_status(self, jobid, private_logger):
        for i in range(180):
            current_status = requests.post("http://corgi.pt.miui.com/open-api/checkBuildStatus",
                                           data={"id": jobid})
            # print(current_status.text)
            result_json = json.loads(current_status.text)
            if result_json.get('status') == 'success':
                url = result_json.get('url')
                private_logger.info("Jenkins构建ROM的任务成功, url地址: %s" % str(url))
                return True, url
            elif result_json.get('status') == 'failure':
                private_logger.info("Jenkins构建ROM的任务失败, url地址: %s" % str(result_json.get('status')))
                return False, None
            else:
                private_logger.info("Jenkins构建ROM的任务当前状态, url地址: %s" % str(result_json.get('status')))
            time.sleep(60)
        return False, None

    def ret(self):
        return True, "url"


if __name__ == "__main__":
    pass
    # # request_package("sagit", "o-dev", "cn")
    # # request_package("sagit", "o-dev", "cn")
    # # request_package("mido", "n-alpha", "cn")
    # # request_package("sagit", "", "cn")
    # check_status(722920)
